//
//  DebugNetWorkRecordDetailViewController.m
//  YK_DebugManager
//
//  Created by edward on 2020/12/29.
//  Copyright © 2020 Edward. All rights reserved.
//

#import "DebugNetWorkRecordDetailViewController.h"
#import "DebugNetWorkManager.h"

#define celllabelWidth (UIScreen.mainScreen.bounds.size.width - 80 - 45)
#pragma mark -----------🔽🔽🔽🔽🔽🔽cell🔽🔽🔽🔽🔽------------
@interface RecordDetailCell : UITableViewCell

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *resposneLabel;
- (void)setData:(NSString *)title resposne:(NSString *)resposne;
@end

@implementation RecordDetailCell



- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        [self setupUI];
    }
    return self;
}
- (void)setupUI
{
    self.backgroundColor = UIColor.clearColor;
    self.contentView.backgroundColor = UIColor.clearColor;
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15 , 15, 80, 20)];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.contentView addSubview:self.titleLabel];
    
    self.resposneLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.titleLabel.frame)+15, CGRectGetMinY(self.titleLabel.frame), celllabelWidth, 20)];
    self.resposneLabel.font = [UIFont systemFontOfSize:15];
    [self.contentView addSubview:self.resposneLabel];
    if (@available(iOS 13.0, *)) {
        self.titleLabel.textColor = UIColor.labelColor;
        self.resposneLabel.textColor = UIColor.labelColor;
    } else {
        self.titleLabel.textColor = UIColor.blackColor;
        self.resposneLabel.textColor = UIColor.blackColor;
    }
}
- (void)setData:(NSString *)title resposne:(NSString *)resposne
{
    self.titleLabel.text = title;
    self.resposneLabel.text = resposne;
    self.resposneLabel.numberOfLines = 0;
    [self.resposneLabel sizeToFit];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
@end

#pragma mark -----------🔼🔼🔼🔼🔼cell🔼🔼🔼🔼🔼------------

@interface DebugNetWorkRecordDetailViewController ()

///
@property(nonatomic,strong) DebugNetWorkModel *record;

@property (nonatomic, strong) NSArray<NSDictionary *> *datas;

@end

@implementation DebugNetWorkRecordDetailViewController

- (instancetype)initWithRecord:(DebugNetWorkModel *)record
{
    self = [super init];
    if (self) {
        if (record) {
            self.record = record;
        }else
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.title = self.record.url.path;
    self.tableView.estimatedRowHeight = 20;
    [self.tableView registerClass:RecordDetailCell.class forCellReuseIdentifier:NSStringFromClass(RecordDetailCell.class)];
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [format setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *reTime = @"";
    if ([self.record.startTime isKindOfClass:NSDate.class]) {
        reTime = [format stringFromDate:self.record.startTime];
    }else
    {
        reTime = [NSString stringWithFormat:@"%@",self.record.startTime];
    }
    NSString *rpTime = @"";
    if ([self.record.endTime isKindOfClass:NSDate.class]) {
        rpTime = [format stringFromDate:self.record.endTime];
    }else
    {
        rpTime = [NSString stringWithFormat:@"%@",self.record.endTime];
    }
    NSUInteger responseHeadersLength = 0;
    if (self.record.response && [self.record.response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)self.record.response;
        NSDictionary<NSString *, NSString *> *headerFields = httpResponse.allHeaderFields;
        if (headerFields) {
            NSData *data = [NSJSONSerialization dataWithJSONObject:headerFields
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:nil];
            responseHeadersLength = data.length;
        }
    }
    NSUInteger requestHeadersLength = 0;
    if (self.record.request && [self.record.request isKindOfClass:NSURLRequest.class]) {
        NSURLRequest *httpRequest = (NSURLRequest *)self.record.request;
        NSDictionary<NSString *, NSString *> *headerFields = httpRequest.allHTTPHeaderFields;
        if (headerFields) {
            NSData *data = [NSJSONSerialization dataWithJSONObject:headerFields
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:nil];
            requestHeadersLength = data.length;
        }
    }
    NSLog(@"🔥data:%@",[[NSString alloc] initWithData:self.record.requestBody encoding:NSASCIIStringEncoding]);
    self.datas = @[
                   @{@"地址":self.record.url},
//                   @{@"类型":self.record.isCache ? @"缓存" : @"网络"},
                   @{@"请求时间":reTime},
                   @{@"响应时间":rpTime},
                   @{@"响应状态":self.record.statusCode},
                   @{@"请求时长":[NSString stringWithFormat:@"%fs",self.record.endTime.timeIntervalSince1970 - self.record.startTime.timeIntervalSince1970]},
                   @{@"请求方式":self.record.method},
                   @{@"mineType":self.record.mineType},
                   @{@"请求长度":[NSString stringWithFormat:@"%@",@(requestHeadersLength)]},
                   @{@"请求头":[NSString stringWithFormat:@"%@",self.record.request.allHTTPHeaderFields]},
                   @{@"请求体":self.record.requestBody!=nil?[[NSString alloc] initWithData:self.record.requestBody encoding:NSUTF8StringEncoding]?:@"":@""},
                   @{@"响应长度":[NSString stringWithFormat:@"%@",@(responseHeadersLength)]},
                   @{@"响应头":[NSString stringWithFormat:@"%@",self.record.request.allHTTPHeaderFields]},
                   @{@"响应体":[[NSString alloc] initWithData:self.record.responseData encoding:NSUTF8StringEncoding]},
    ];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(share:)];
    self.navigationItem.rightBarButtonItem = item;
}
- (void)share:(UIBarButtonItem *)item
{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSMutableString *string = [NSMutableString string];
    [self.datas enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [string appendFormat:@"%@   %@\n",obj.allKeys.firstObject?:@"",obj.allValues.firstObject];
    }];
    NSString *cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",[[NSString stringWithFormat:@"%@",self.record.url] stringByReplacingOccurrencesOfString:@"/" withString:@"_"]]];
//    NSString *cachesPath = @"";
    if ([manager fileExistsAtPath:cachesPath]) {
        [manager removeItemAtPath:cachesPath error:nil];
    }
    NSError *err;
    [string writeToFile:cachesPath atomically:YES encoding:NSUTF8StringEncoding error:&err];
    if (!err) {
    UIActivityViewController *docVc = [[UIActivityViewController alloc] initWithActivityItems:@[[NSURL fileURLWithPath:cachesPath]] applicationActivities:nil];
        [self presentViewController:docVc animated:YES completion:nil];
    }
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RecordDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(RecordDetailCell.class) forIndexPath:indexPath];
    NSDictionary *dic = (NSDictionary *)self.datas[indexPath.row];
    NSString *key = [dic allKeys][0];
    NSString *value = [[[dic valueForKey:key] stringByReplacingOccurrencesOfString:@"\r" withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    [cell setData:key resposne:value];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.datas[indexPath.row];
    NSString *key = [dic allKeys][0];
    NSString *value = [dic valueForKey:key];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:key message:value preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.datas[indexPath.row];
    NSString *key = [dic allKeys][0];
    NSString *value = [dic valueForKey:key];
    UITextView *tempTextView = [[UITextView alloc] init];
    tempTextView.font = [UIFont systemFontOfSize:15];
    tempTextView.text = value;
    CGSize fontSize = [tempTextView sizeThatFits:CGSizeMake(celllabelWidth, MAXFLOAT)];
    return fontSize.height;
}
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    if (action == @selector(copy:)) {
        return YES;
    } else {
        return NO;
    }
}
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender
{
    if (action == @selector(copy:)) {
        NSDictionary *data = self.datas[indexPath.row];
        [UIPasteboard generalPasteboard].string = data.allValues.firstObject;
    }
}
@end
